<template>
    <view class="admin-page">
        <!-- 加载中遮罩 -->
        <view v-if="isLoading" class="loading-mask">
            <view class="loading-content">
                <view class="loading-spinner">
                    <text class="fa fa-circle-o-notch"></text>
                </view>
                <text>正在验证管理员身份...</text>
            </view>
        </view>

        <!-- 管理员内容 -->
        <view v-else class="admin-container" :class="{ 'mobile': isMobile, 'dark': isDarkMode }">
            <!-- 统一的页面头部 -->
            <view class="admin-header">
                <h1 class="header-title">
                    <i class="fa fa-shield-alt"></i> 管理后台
                </h1>
                <view class="header-right">
                    <view class="admin-profile" v-if="adminInfo">
                        <image class="profile-avatar" :src="adminInfo.avatar || '/static/default-avatar.png'" mode="aspectFill" />
                        <text class="profile-name">{{ adminInfo.name }}</text>
                </view>
                    <button class="back-btn" @click="goToHome">
                        <i class="fa fa-home"></i>
                        <text class="btn-text-desktop"> 回到首页</text>
                </button>
                </view>
            </view>

            <!-- 主要内容区 -->
            <view class="main-content">
                <!-- 左侧菜单 -->
                <view class="side-menu">
                    <scroll-view class="menu-scroll" :scroll-y="!isMobile" :scroll-x="isMobile">
                    <view 
                            v-for="item in menuItems" 
                            :key="item.key"
                            class="menu-item"
                            :class="{'active': currentTab === item.key}"
                            @tap="switchTab(item.key)"
                        >
                            <i :class="'fa fa-' + item.icon"></i>
                            <text>{{ item.label }}</text>
                        </view>
                    </scroll-view>
                    </view>

                <!-- 右侧内容区 -->
                <view class="content-area">
                    <!-- 数据概览 -->
                    <view v-if="currentTab === 'dashboard'" class="dashboard">
                        <view class="stats-grid">
                            <view v-for="(stat, index) in statistics" :key="index" class="stat-card">
                                <view class="stat-header">
                                    <text>{{ stat.label }}</text>
                                    <text :class="'fa fa-' + stat.icon"></text>
                                </view>
                                <text class="stat-value">{{ stat.value }}</text>
                                <text class="stat-change">{{ stat.change }}</text>
                            </view>
                        </view>
                    </view>

                    <!-- 用户管理 -->
                    <view v-if="currentTab === 'users'" class="users-section">
                        <!-- 搜索和筛选栏 -->
                        <view class="control-bar">
                            <view class="search-box">
                                <input 
                                    type="text" 
                                    v-model="userSearchQuery"
                                    placeholder="搜索用户..." 
                                    @confirm="handleSearch"
                                />
                                <button class="search-btn" @tap="handleSearch">
                                    <text class="fa fa-search"></text>
                                </button>
                            </view>
                            
                            <view class="filter-box">
                                <select 
                                    v-model="userFilter"
                                    @change="handleFilterChange"
                                    class="filter-select"
                                >
                                    <option 
                                        v-for="option in userFilterOptions"
                                        :key="option.value"
                                        :value="option.value"
                                    >
                                        {{ option.label }}
                                    </option>
                                </select>
                                
                                <select 
                                    v-model="userSort"
                                    @change="handleSortChange"
                                    class="sort-select"
                                >
                                    <option 
                                        v-for="option in userSortOptions"
                                        :key="option.value"
                                        :value="option.value"
                                    >
                                        {{ option.label }}
                                    </option>
                                </select>
                            </view>
                    </view>

                        <!-- 用户列表 -->
                        <view class="user-table">
                            <table v-if="!isUserLoading && users.length > 0">
                                <thead>
                                    <tr>
                                        <th>用户ID</th>
                                        <th>用户信息</th>
                                        <th>邮箱</th>
                                        <th>角色</th>
                                        <th>等级</th>
                                        <th>注册时间</th>
                                        <th>状态</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="user in filteredUsers" :key="user.id">
                                        <template v-if="user">
                                        <td>{{ user.ID }}</td>
                                        <td class="user-info">
                                            <image :src="user.avatar || '/static/default-avatar.png'" mode="aspectFill"/>
                                            <text>{{ user.name }}</text>
                                        </td>
                                        <td>{{ user.email }}</td>
                                        <td>
                                            <text :class="['role-badge', user.role]">
                                                {{ user.role === 'admin' ? '管理员' : '用户' }}
                                            </text>
                                        </td>
                                        <td>Lv.{{ user.level || 1 }}</td>
                                        <td>{{ user.registerDate }}</td>
                                        <td>
                                            <text :class="['status-badge', user.status]">
                                                {{ user.status === 'active' ? '正常' : '已封禁' }}
                                            </text>
                                        </td>
                                        <td class="actions">
                                            <button 
                                                class="action-btn edit" 
                                                @tap="openEditModal(user)"
                                                v-if="user.role !== 'admin'"
                    >
                                                <text class="fa fa-edit"></text>
                                            </button>
                                            <button 
                                                :class="['action-btn', user.status === 'active' ? 'ban' : 'unban']"
                                                @tap="toggleUserStatus(user)"
                                                v-if="user.role !== 'admin'"
                                            >
                                                <text :class="'fa fa-' + (user.status === 'active' ? 'ban' : 'check')"></text>
                                            </button>
                                            <button 
                                                class="action-btn delete"
                                                @tap="handleDeleteUser(user.id)"
                                                v-if="user.role !== 'admin'"
                                            >
                                                <text class="fa fa-trash"></text>
                                            </button>
                                        </td>
                                        </template>
                                    </tr>
                                </tbody>
                            </table>
                            
                            <!-- 加载中状态 -->
                            <view v-if="isUserLoading" class="loading-state">
                                <text class="fa fa-spinner fa-spin"></text>
                                <text>加载中...</text>
                            </view>
                            
                            <!-- 空数据状态 -->
                            <view v-if="!isUserLoading && users.length === 0" class="empty-state">
                                <text class="fa fa-users"></text>
                                <text>暂无用户数据</text>
                    </view>
                </view>

                        <!-- 分页 -->
                        <view class="pagination">
                            <button 
                                class="page-btn"
                                :disabled="userPagination.page === 1"
                                @tap="handlePageChange(userPagination.page - 1)"
                            >
                                <text class="fa fa-chevron-left"></text>
                            </button>
                            <text class="page-info">
                                第 {{ userPagination.page }} 页 / 共 {{ Math.ceil(userPagination.total / userPagination.pageSize) }} 页
                            </text>
                            <button 
                                class="page-btn"
                                :disabled="userPagination.page >= Math.ceil(userPagination.total / userPagination.pageSize)"
                                @tap="handlePageChange(userPagination.page + 1)"
                            >
                                <text class="fa fa-chevron-right"></text>
                            </button>
                    </view>

                        <!-- 编辑用户弹窗 -->
                        <uni-popup ref="editUserPopup" type="dialog">
                            <view class="edit-modal" v-if="editingUser">
                                <view class="modal-header">
                                    <text class="modal-title">编辑用户信息</text>
                                    <button class="close-btn" @tap="closeEditModal">
                                        <text class="fa fa-times"></text>
                                    </button>
                                </view>
                                
                                <view class="modal-body">
                                    <view class="form-group">
                                        <label>用户名</label>
                                        <input type="text" v-model="editingUser.name"/>
                                    </view>
                                    <view class="form-group">
                                        <label>邮箱</label>
                                        <input type="email" v-model="editingUser.email"/>
                                    </view>
                                    <view class="form-group">
                                        <label>等级</label>
                                        <input type="number" v-model="editingUser.level"/>
                                    </view>
                                    <view class="form-group">
                                        <label>角色</label>
                                        <select v-model="editingUser.role">
                                            <option value="user">普通用户</option>
                                            <option value="admin">管理员</option>
                                        </select>
                                    </view>
                                </view>
                                
                                <view class="modal-footer">
                                    <button class="btn-cancel" @tap="closeEditModal">取消</button>
                                    <button class="btn-confirm" @tap="saveUserEdit">保存</button>
                                </view>
                            </view>
                        </uni-popup>
                    </view>

                    <!-- 动态管理 -->
                    <view v-if="currentTab === 'posts'" class="posts-section">
                        <view class="control-bar">
                            <view class="search-box">
                                <input type="text" v-model="postSearchQuery" placeholder="搜索动态内容..." @confirm="fetchPosts" />
                                <button class="search-btn" @tap="fetchPosts"><text class="fa fa-search"></text></button>
                            </view>
                        </view>

                        <view class="post-table">
                            <table v-if="!isPostLoading && posts.length > 0">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>作者</th>
                                        <th>内容</th>
                                        <th>点赞数</th>
                                        <th>发布时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="post in posts" :key="post.id">
                                        <template v-if="post">
                                        <td>{{ post.id }}</td>
                                        <td class="user-info">
                                            <image :src="post.User && post.User.avatar || '/static/default-avatar.png'" mode="aspectFill" />
                                            <text>{{ post.User ? post.User.name : '未知用户' }}</text>
                                        </td>
                                        <td class="content-cell">{{ post.content }}</td>
                                        <td>{{ post.likes }}</td>
                                        <td>{{ formatDate(post.created_at) }}</td>
                                        <td class="actions">
                                            <button class="action-btn delete" @tap="handleDeletePost(post.id)">
                                                <text class="fa fa-trash"></text>
                                            </button>
                                        </td>
                                        </template>
                                    </tr>
                                </tbody>
                            </table>
                            <view v-if="isPostLoading" class="loading-state">
                                <text class="fa fa-spinner fa-spin"></text>
                                <text>加载中...</text>
                            </view>
                            <view v-if="!isPostLoading && posts.length === 0" class="empty-state">
                                <text class="fa fa-file-alt"></text>
                                <text>暂无动态数据</text>
                            </view>
                        </view>
                    </view>

                    <!-- 公告管理 -->
                    <view v-if="currentTab === 'notices'" class="notices-section">
                        <view class="notice-form-card">
                            <view class="form-header">
                                <text class="fa fa-bullhorn"></text>
                                <text>发布新公告</text>
                            </view>
                            <view class="form-group">
                                <input type="text" v-model="newNotice.title" placeholder="公告标题" />
                            </view>
                            <view class="form-group">
                                <textarea v-model="newNotice.content" placeholder="公告内容..." />
                            </view>
                            <button class="submit-btn" @tap="handleCreateNotice" :disabled="isSubmitting">
                                {{ isSubmitting ? '发布中...' : '立即发布' }}
                            </button>
                        </view>

                        <view class="notice-list">
                            <view v-if="isNoticeLoading" class="loading-state"><text>加载公告中...</text></view>
                            <view v-else-if="notices.length === 0" class="empty-state"><text>暂无公告</text></view>
                            <view v-else class="notice-item" v-for="notice in notices" :key="notice.id">
                                <view class="item-header">
                                    <text class="item-title">{{ notice.title }}</text>
                                    <text class="item-date">{{ formatDate(notice.created_at) }}</text>
                                </view>
                                <text class="item-content">{{ notice.content }}</text>
                                <button class="item-delete-btn" @tap="handleDeleteNotice(notice.id)">
                                    <text class="fa fa-trash"></text>
                                </button>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import {
	getSystemStats,
	getAllUsers,
	updateUser,
	deleteUser,
	getAllPostsAdmin,
	deletePostAdmin,
	createNotice,
	getAllNoticesAdmin,
	deleteNoticeAdmin
} from '@/api/admin'
import {
	getUserInfo
} from '@/api/user'
import { useUserStore } from '@/stores/user';
import { checkLoginStatus, checkAdminRole, getCurrentUserInfo } from '@/utils/auth';
import UniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue';

export default {
    components: {
        UniPopup
    },
    data() {
        return {
            isLoading: false,
            adminInfo: null,
            adminName: '',
            currentTab: 'dashboard',
            notices: [],
            newNotice: {
                title: '',
                content: ''
            },
            menuItems: [
                { key: 'dashboard', label: '数据概览', icon: 'dashboard' },
                { key: 'users', label: '用户管理', icon: 'users' },
                { key: 'posts', label: '动态管理', icon: 'th-large' },
                { key: 'notices', label: '公告管理', icon: 'bullhorn' }
            ],
            statistics: [
                { 
                    label: '总用户数', 
                    value: '1,234', 
                    change: '较上月增长 5.2%',
                    icon: 'users',
                    color: 'text-blue-500'
                },
                { 
                    label: '动态数', 
                    value: '8,567', 
                    change: '较上月增长 12.3%',
                    icon: 'comments',
                    color: 'text-green-500'
                },
                { 
                    label: '活跃用户', 
                    value: '892', 
                    change: '较上月增长 8.7%',
                    icon: 'user-circle',
                    color: 'text-purple-500'
                }
            ],
            users: [],
            userSearchQuery: '',
            userFilter: 'all',
            userPagination: {
                page: 1,
                pageSize: 10,
                total: 0
            },
            userSort: {
                field: 'created_at',
                order: 'desc'
            },
            isUserLoading: false,
            editingUser: null,
            showUserModal: false,
            userFilterOptions: [
                { label: '全部用户', value: 'all' },
                { label: '正常用户', value: 'active' },
                { label: '已封禁', value: 'banned' },
                { label: '已注销', value: 'deleted' }
            ],
            userSortOptions: [
                { label: '注册时间', value: 'created_at' },
                { label: '用户等级', value: 'level' },
                { label: '用户ID', value: 'id' }
            ],
            posts: [],
            postSearchQuery: '',
            postFilter: 'all',
            isMobile: false,
            isDarkMode: false,
            adminInfo: null,
            isSubmitting: false,
            loadedTabs: {
                users: false,
                posts: false,
                notices: false,
            },
            stats: {
                users: 0,
                posts: 0,
                activity: 0,
                newUsers: 0
            },
            isPostLoading: false,
            isNoticeLoading: false,
        }
    },
    computed: {
        getCurrentTabLabel() {
            const item = this.menuItems.find(item => item.key === this.currentTab)
            return item ? item.label : ''
        },
        filteredUsers() {
            let result = [...this.users]
            
            // 搜索过滤
            if (this.userSearchQuery) {
                const query = this.userSearchQuery.toLowerCase()
                result = result.filter(user => 
                    user.name.toLowerCase().includes(query) ||
                    user.email.toLowerCase().includes(query) ||
                    user.id.toString().includes(query)
                )
            }
            
            // 状态过滤
            if (this.userFilter !== 'all') {
                result = result.filter(user => user.status === this.userFilter)
            }
            
            return result
        },
        sortOrderIcon() {
            return this.userSort.order === 'desc' ? 'fa-sort-down' : 'fa-sort-up'
        }
    },
    onReady() {
        this.checkAdminRole()
    },
    onLoad() {
        const systemInfo = uni.getSystemInfoSync();
        this.isMobile = systemInfo.windowWidth < 768;
        this.isTablet = systemInfo.windowWidth >= 768 && systemInfo.windowWidth < 1024;
        this.isDesktop = systemInfo.windowWidth >= 1024;
        this.loadStats();
    },
    onPullDownRefresh() {
        this.fetchData();
    },
    methods: {
        // 加载统计数据（初始加载）
        async loadStats() {
            this.isLoading = true;
            try {
                const statsRes = await getSystemStats();
                if (statsRes && statsRes.user_stats) {
                    this.stats.users = statsRes.user_stats.total || 0;
                    this.stats.posts = statsRes.post_stats.total || 0;
                    this.stats.activity = statsRes.user_stats.total > 0 ? Math.floor((statsRes.user_stats.active / statsRes.user_stats.total) * 100) : 0;
                    this.stats.newUsers = statsRes.user_stats.new_last_24h || 0;
                }
            } catch (error) {
                console.error("获取统计数据失败:", error);
                uni.showToast({ title: '统计数据加载失败', icon: 'error' });
            } finally {
                this.isLoading = false;
            }
        },
        // 切换标签页并按需加载数据
        async switchTab(tab) {
            this.currentTab = tab;
            if (this.loadedTabs[tab] || tab === 'dashboard') {
                return;
            }
            
            this.isLoading = true;
            try {
                switch (tab) {
                    case 'users':
                        this.users = await getAllUsers();
                        break;
                    case 'posts':
                        try {
                            const result = await getAllPostsAdmin();
                            console.log('动态数据API结果:', result);
                            
                            // 处理不同的响应格式
                            if (Array.isArray(result)) {
                                // 直接返回数组格式
                                this.posts = result;
                            } else if (result && result.data && Array.isArray(result.data)) {
                                // 包含在data字段中的数组
                                this.posts = result.data;
                            } else if (result && result.code === 200 && result.data) {
                                // 标准成功响应格式
                                this.posts = Array.isArray(result.data) ? result.data : [];
                            } else {
                                // 其他情况，设置为空数组
                                this.posts = [];
                                console.warn('动态数据格式不符合预期:', result);
                            }
                            
                            console.log('switchTab 最终设置的posts数据:', this.posts);
                        } catch (error) {
                            this.posts = [];
                            console.error('获取动态数据时发生异常:', error);
                            uni.showToast({
                                title: '加载动态失败: ' + error.message,
                                icon: 'none',
                                duration: 3000
                            });
                        }
                        break;
                    case 'notices':
                        this.notices = await getAllNoticesAdmin();
                        break;
                }
                this.loadedTabs[tab] = true;
            } catch (error) {
                console.error(`加载 ${tab} 数据失败:`, error);
                uni.showToast({ title: '数据加载失败', icon: 'error' });
            } finally {
                this.isLoading = false;
            }
        },
        // 重新加载公告
        async reloadNotices() {
            this.isLoading = true;
            try {
                this.notices = await getAllNoticesAdmin();
            } catch (error) {
                uni.showToast({ title: '公告刷新失败', icon: 'error' });
            } finally {
                this.isLoading = false;
            }
        },
        // 检查管理员权限
        async checkAdminRole() {
            // 使用统一的管理员检查函数
            if (!checkAdminRole()) {
                // 如果不是管理员，跳转到首页
                if (!checkLoginStatus()) {
                    // 如果未登录，跳转到登录页
                    uni.reLaunch({ url: '/pages/login/login' });
                } else {
                    // 如果已登录但不是管理员，跳转到首页
                    uni.reLaunch({ url: '/pages/home/home' });
                }
                return;
            }
            
            try {
                // 使用统一的用户信息获取函数
                const userInfo = getCurrentUserInfo();
                const userId = userInfo ? userInfo.userId : null;
                if (!userId) {
                    uni.reLaunch({ url: '/pages/login/login' });
                    return;
                }

                const userData = await getUserInfo(userId);
                this.adminName = userData.name;
                this.adminInfo = userData;
                const userStore = useUserStore();
                userStore.role = userData.role;
                this.isLoading = false;
                // 初始化时加载第一个标签页的数据
                this.fetchDataForCurrentTab();
            } catch (error) {
                console.error('验证管理员权限失败:', error);
                uni.showToast({
                    title: '验证管理员权限失败',
                    icon: 'none'
                });
                uni.reLaunch({ url: '/pages/login/login' });
            }
        },
        // 加载公告列表
        async loadNotices() {
            this.isNoticeLoading = true;
            try {
                const response = await getAllNoticesAdmin()
                this.notices = response || [];
            } catch (error) {
                console.error('加载公告列表失败:', error)
                this.notices = []
            } finally {
                this.isNoticeLoading = false;
            }
        },
        // 创建公告
        async handleCreateNotice() {
            if (!this.newNotice.title.trim() || !this.newNotice.content.trim()) {
                uni.showToast({
                    title: '请填写完整信息',
                    icon: 'none'
                })
                return
            }
             this.isSubmitting = true;
            try {
                await createNotice({
                    title: this.newNotice.title.trim(),
                    content: this.newNotice.content.trim()
                })
                
                uni.showToast({
                    title: '发布成功',
                    icon: 'success'
                })
                
                this.newNotice.title = ''
                this.newNotice.content = ''
                
                await this.loadNotices()
            } catch (error) {
                uni.showToast({
                    title: error.message || '发布失败',
                    icon: 'none'
                })
            } finally {
                this.isSubmitting = false;
            }
        },
        // 删除公告
        async handleDeleteNotice(noticeId) {
            uni.showModal({
                title: '提示',
                content: '确定要删除这条公告吗？',
                success: async (res) => {
                    if (res.confirm) {
                        try {
                            await deleteNoticeAdmin(noticeId)
                            
                            uni.showToast({
                                title: '删除成功',
                                icon: 'success'
                            })
                            
                            await this.loadNotices()
                        } catch (error) {
                            uni.showToast({
                                title: error.message || '删除失败',
                                icon: 'none'
                            })
                        }
                    }
                }
            })
        },
        // 加载用户列表
        async loadUsers() {
            try {
                this.isUserLoading = true
                const params = {
                    page: this.userPagination.page,
                    pageSize: this.userPagination.pageSize,
                    sort: this.userSort.field,
                    order: this.userSort.order
                }
                if (this.userFilter !== 'all') {
                    params.status = this.userFilter;
                }
                if (this.userSearchQuery) {
                    params.search = this.userSearchQuery;
                }
                
                console.log('加载用户列表，参数:', params)
                
                const response = await getAllUsers(params)
                if (response && response.data) {
                    console.log('用户列表加载成功:', response)
                    this.users = response.data.map(user => ({
                        ...user,
                        registerDate: user.created_at ? new Date(user.created_at).toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }) : '未知',
                    }))
                    this.userPagination.total = response.total || 0
                    this.userPagination.page = response.page || 1
                    this.userPagination.pageSize = response.pageSize || 10
                } else {
                    this.users = []
                    this.userPagination.total = 0
                }
            } catch (error) {
                console.error('加载用户列表失败:', error)
            uni.showToast({
                    title: error.message || '加载用户列表失败',
                    icon: 'none',
                    duration: 2000
                })
            } finally {
                this.isUserLoading = false
            }
        },
        // 打开编辑用户弹窗
        openEditModal(user) {
            this.editingUser = { ...user }
            this.$refs.editUserPopup.open()
        },
        // 关闭编辑用户弹窗
        closeEditModal() {
            this.$refs.editUserPopup.close()
            this.editingUser = null
        },
        // 保存用户编辑
        async saveUserEdit() {
            try {
                if (!this.editingUser || !this.editingUser.id) {
                    throw new Error('无效的用户数据')
                }

                const updateData = {
                    name: this.editingUser.name,
                    email: this.editingUser.email,
                    role: this.editingUser.role,
                    level: this.editingUser.level
                }

                console.log('更新用户信息:', {
                    userId: this.editingUser.id,
                    data: updateData
                })

                await updateUser(this.editingUser.id, updateData)
                
                uni.showToast({
                    title: '更新成功',
                    icon: 'success'
                })
                
                this.closeEditModal()
                await this.loadUsers()
            } catch (error) {
                console.error('更新用户失败:', error)
                uni.showToast({
                    title: error.message || '更新失败',
                    icon: 'none',
                    duration: 2000
                })
            }
        },
        // 切换用户状态
        async toggleUserStatus(user) {
            const newStatus = user.status === 'active' ? 'banned' : 'active';
            const confirmTitle = newStatus === 'banned' ? `确认封禁用户 ${user.name} 吗？` : `确认解封用户 ${user.name} 吗？`;

            uni.showModal({
                title: '请确认',
                content: confirmTitle,
                success: async (res) => {
                    if (res.confirm) {
                        try {
                            // 使用 updateUser 更新用户状态
                            await updateUser(user.id, {
                                status: newStatus
                            });
                            // 更新成功后，在前端直接修改状态
                            user.status = newStatus;
                            uni.showToast({
                                title: `操作成功`,
                                icon: 'success'
                            });
                        } catch (error) {
                            console.error("更新用户状态失败:", error);
                            uni.showToast({
                                title: '操作失败',
                                icon: 'error'
                            });
                        }
                    }
                }
            });
        },
        // 删除用户
        async handleDeleteUser(userId) {
            try {
                const modalRes = await uni.showModal({
                    title: '确认删除',
                    content: '确定要删除这个用户吗？此操作不可恢复。',
                    showCancel: true
                })

                if (!modalRes.confirm) {
                    return
                }

                console.log('发送删除请求:', { userId })
                
                await deleteUser(userId)
                
                uni.showToast({
                    title: '删除成功',
                    icon: 'success'
                })
                
                await this.loadUsers()
            } catch (error) {
                console.error('删除用户失败:', error)
                uni.showToast({
                    title: error.message || '删除失败',
                    icon: 'none',
                    duration: 2000
                })
            }
        },
        // 处理排序变化
        handleSortChange(event) {
            const value = event.target.value
            const option = this.userSortOptions.find(opt => opt.value === value)
            if (option) {
                this.userSort.field = value
                this.loadUsers()
            }
        },
        // 处理筛选变化
        handleFilterChange(event) {
            const value = event.target.value
            const option = this.userFilterOptions.find(opt => opt.value === value)
            if (option) {
                this.userFilter = value
                this.userPagination.page = 1 // 重置页码
                this.loadUsers()
            }
        },
        // 处理搜索
        handleSearch() {
            this.userPagination.page = 1 // 重置页码
            this.loadUsers()
        },
        // 处理页码变化
        handlePageChange(page) {
            this.userPagination.page = page
            this.loadUsers()
        },
        // 切换排序顺序
        toggleSortOrder() {
            this.userSort.order = this.userSort.order === 'desc' ? 'asc' : 'desc'
            this.loadUsers()
        },
        // 导航到首页
        goToHome() {
            uni.reLaunch({
                url: '/pages/home/home'
            })
        },
        // 在页面加载时调用
        async initializeAdmin() {
            try {
                await this.checkAdminRole()
            } catch (error) {
                console.error('初始化失败:', error)
            }
        },
        // 格式化日期
        formatDate(dateString) {
            if (!dateString) return 'N/A';
            const date = new Date(dateString);
            return date.toLocaleString();
        },
        // 获取头像URL (需要一个默认头像)
        getAvatarUrl(avatarData) {
            // 实际项目中,这里可以根据avatarData动态生成URL或返回一个默认图
            return '/static/default-avatar.png';
        },
        // 删除动态
        async handleDeletePost(postId) {
            uni.showModal({
                title: '请确认',
                content: `确定要删除该动态吗？(ID: ${postId})`,
                success: async (res) => {
                    if (res.confirm) {
                        try {
                            await deletePostAdmin(postId);
                            uni.showToast({ title: '删除成功', icon: 'success' });
                            // 重新加载动态列表
                            await this.fetchPosts();
                        } catch (error) {
                            console.error("删除动态失败:", error);
                            uni.showToast({ title: '删除失败', icon: 'error' });
                        }
                    }
                }
            });
        },
        // 删除动态（旧方法，保持兼容性）
        confirmDeletePost(post) {
            this.handleDeletePost(post.id);
        },
        async fetchAdminInfo() {
            try {
                const userStore = useUserStore();
                this.adminInfo = await getUserInfo(userStore.userId);
            } catch (error) {
                console.error('获取管理员信息失败:', error);
            }
        },
        async fetchDataForCurrentTab() {
            const tab = this.currentTab;
            if (this.loadedTabs[tab]) return;

            this.isLoading = true;
            try {
                 switch (tab) {
                    case 'users':
                        await this.loadUsers();
                        break;
                    case 'posts':
                        await this.fetchPosts();
                        break;
                    case 'notices':
                        await this.loadNotices();
                        break;
                    case 'dashboard':
                         await this.loadStats();
                         break;
                }
                this.loadedTabs[tab] = true;
            } catch (e) {
                console.error(`加载 ${tab} 数据失败`, e)
            } finally {
                this.isLoading = false;
            }
        },
        async fetchPosts() {
            this.isPostLoading = true;
            try {
                const params = {
                    search: this.postSearchQuery,
                };
                // 获取动态数据
                const response = await getAllPostsAdmin(params);
                console.log('fetchPosts 响应:', response);
                
                // 处理不同的响应格式
                if (Array.isArray(response)) {
                    // 直接返回数组格式
                    this.posts = response;
                } else if (response && response.data && Array.isArray(response.data)) {
                    // 包含在data字段中的数组
                    this.posts = response.data;
                } else if (response && response.code === 200 && response.data) {
                    // 标准成功响应格式
                    this.posts = Array.isArray(response.data) ? response.data : [];
                } else {
                    // 其他情况，设置为空数组
                    this.posts = [];
                    console.warn('动态数据格式不符合预期:', response);
                }
                
                console.log('最终设置的posts数据:', this.posts);
            } catch (error) {
                console.error("加载动态列表失败:", error);
                this.posts = [];
                uni.showToast({ title: '动态加载失败', icon: 'error' });
            } finally {
                this.isPostLoading = false;
            }
        },
    },
    watch: {
        currentTab: {
            handler(newTab) {
                this.fetchDataForCurrentTab();
            },
            immediate: true
        }
    },
    mounted() {
        this.initializeAdmin()
    }
}
</script>

<style src="./admin.css"></style>